package dao;

import db.DatabaseManager;
import model.Customer;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CustomerDao {

    public List<Customer> getAllCustomers() {
        List<Customer> customers = new ArrayList<>();
        String sql = "SELECT * FROM customers";

        try (Connection conn = DatabaseManager.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                Customer customer = new Customer(
                        rs.getString("id"),
                        rs.getString("name"),
                        rs.getString("phone"),
                        rs.getString("email")
                );
                customers.add(customer);
            }
        } catch (SQLException e) {
            System.out.println("查询客户信息失败: " + e.getMessage());
        }
        return customers;
    }

    public void addCustomer(Customer customer) {
        String sql = "INSERT INTO customers(id, name, phone, email) VALUES(?,?,?,?)";

        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, customer.getId());
            pstmt.setString(2, customer.getName());
            pstmt.setString(3, customer.getPhone());
            pstmt.setString(4, customer.getEmail());
            pstmt.executeUpdate();

        } catch (SQLException e) {
            System.out.println("添加客户失败: " + e.getMessage());
        }
    }

    public Customer findCustomerById(String id) {
        String sql = "SELECT * FROM customers WHERE id = ?";
        Customer customer = null;

        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, id);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                customer = new Customer(
                        rs.getString("id"),
                        rs.getString("name"),
                        rs.getString("phone"),
                        rs.getString("email")
                );
            }
        } catch (SQLException e) {
            System.out.println("查询客户失败: " + e.getMessage());
        }
        return customer;
    }

    public void deleteCustomer(String id) {
        String sql = "DELETE FROM customers WHERE id = ?";

        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, id);
            pstmt.executeUpdate();

        } catch (SQLException e) {
            System.out.println("删除客户失败: " + e.getMessage());
        }
    }
}